#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define MAX_LISTEN_NUM 5
#define SEND_BUF_SIZE 100
#define RECV_BUF_SIZE 100
#define SERVER_PORT 16901

int main(int argc, char* argv[])
{
    int sock_fd = 0;

    // 服务器的socket通讯地址
    struct sockaddr_in ser_addr;

    memset(&ser_addr, 0, sizeof(ser_addr));

    ser_addr.sin_family = AF_INET;
    inet_aton("127.0.0.1", &ser_addr.sin_addr);
    ser_addr.sin_port = htons(SERVER_PORT);

    sock_fd = socket(AF_INET, SOCK_STREAM, 0);

    if (sock_fd < 0) {
        perror("create socket failed\n");
        exit(1);
    }

    if (connect(sock_fd, (struct sockaddr*)&ser_addr, sizeof(ser_addr)) < 0) {
        perror("connect socket failed\n");
        close(sock_fd);
        exit(1);
    }

    unsigned char sendbuf[SEND_BUF_SIZE] = { 0 };
    unsigned int ch;
    int len = 0;

    while (~scanf("%02x", &ch))
        sendbuf[len++] = (unsigned char)ch;

    int n = send(sock_fd, sendbuf, len, 0);

    if (n < 0) {
        perror("send data error\n");
        close(sock_fd);
        exit(1);
    }

    unsigned char recvbuf[RECV_BUF_SIZE] = { 0 };
    n = read(sock_fd, recvbuf, RECV_BUF_SIZE);

    if (n < 0) {
        perror("recv data error\n");
        close(sock_fd);
        exit(1);
    }

    printf("\nReceived: --------- \n");
    for (int i = 0; i < n; ++i)
        printf("%02X ", recvbuf[i]);

    putchar('\n');

    close(sock_fd);

    return 0;
}
